package com.learn.netty.bio.multithread;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketAddress;

public class SocketHandler implements Runnable {

    private Socket socket;
    private InputStream inputStream;
    private OutputStream outputStream;

    public SocketHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            SocketAddress remoteSocketAddress = socket.getRemoteSocketAddress();
            PrintUtils.printLog("handler socket: " + remoteSocketAddress);
            inputStream = socket.getInputStream();
            handler(remoteSocketAddress);
            PrintUtils.printLog("close socket: " + remoteSocketAddress);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) outputStream.close();
                if (inputStream != null) inputStream.close();
                if (socket != null) socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void handler(SocketAddress remoteSocketAddress) throws IOException {
        byte[] buffer = new byte[1024];
        while (inputStream.read(buffer) > -1) { // blocking
            System.out.println("recv: " + new String(buffer));

            outputStream = socket.getOutputStream();
            outputStream.write("seccess".getBytes()); // blocking
            System.out.println("send msg to " + remoteSocketAddress);
        }
    }
}
